#!/bin/sh
# Windows Install
# By Sergey_Galan (Serhii Halaniuk)
# Copyright (c) 2024, Sergey_Galan (Serhii Halaniuk). All Right Reserved
# Credit: Wimlib, ntfs-3g-utils, Platypus, BCD-SYS



Time()
{
finishTime=$(date -u "+%s")
processedTime=$(expr $finishTime - $startTime)
if [[ $processedTime -gt 3599 ]]; then
    processedTime=$(printf "%dh%dm%ds\n" $((processedTime/3600%3600)) $((processedTime/60%60)) $((processedTime%60)))
elif [[ $processedTime -gt 59 ]]; then
    processedTime=$(printf "%dm%ds\n" $((processedTime/60%60)) $((processedTime%60)))
 else
    processedTime=$(printf "%ds\n" $((processedTime)))
fi
}


DiscNotPermitted()
{
lan=`defaults read -g AppleLocale | cut -d "_" -f1`
if [[ "$lan" = "ru" ]]; then
    echo "Info:\r\r\r"Доступ к диску должен быть предоставлен!"\r"macOS Mojave 10.14 и новее:"\r"Перейдите к Системным настройкам своего Mac, откройте окно Конфиденциальность и безопасность \> вкладка Конфиденциальность \> папка Доступ к диску. Щелкните по блокировке и введите пароль администратора, чтобы позволить изменения. Разрешите доступ \"Windows Install\". Отключите SIP macOS High Sierra 10.13 и новее. Диск не должен быть системным для установки Windows legacy boot. Возможно диск занят посторонним процессом, перезагрузите систему и попробуйте ещё раз запустить установку Виндовс.""

elif [[ "$lan" = "uk" ]]; then
    echo "Info:\r\r\r"Доступ до диска має бути наданий!"\r"macOS Mojave 10.14 та новіше:"\r"Перейдіть до Системних параметрів Mac, відкрийте вікно Приватність і безпека \> вкладка Приватність \> папка Повний доступ до диска. Натисніть на блокування і введіть пароль адміністратора, щоб дозволити зміни. Надайте доступ \"Windows Install\". Вимкніть SIP у macOS High Sierra 10.13 та новіше. Диск не повинен бути системним для інсталяції Windows legacy boot. Можливо диск зайнятий стороннім процесом, перезавантажте систему і спробуйте ще раз запустити установку Віндовс.""

else
    echo "Info:\r\r\r\r"Disk access must be granted!"\r"macOS Mojave 10.14 and later:"\r"Go to your Mac\’s System Preferences, open Security \& Privacy window \> Privacy tab \> Full Disk Access folder. Click the lock and enter an administrator password to allow changes. Check the \"Windows Install\" check box. Disable SIP in macOS High Sierra 10.13 and later. To install Windows legacy boot, the disk must not be the system one. The disk may be occupied by a foreign process, reboot the system and try running the Windows installation again.""
fi
}


DiskPartition()
{
s=s
lan=`defaults read -g AppleLocale | cut -d "_" -f1`
echo "STOP! Disk and/or partition disk$x$s$y doesn\'\t exist!"
if [[ "$lan" = "ru" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Диск и/или раздел disk$x$s$y не существует!"\r"Введите правильные значения диск, раздел в меню программы.""
    exit 1
fi
if [[ "$lan" = "uk" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Диск і/або розділ disk$x$s$y не існує!"\r"Введіть правильні значення диск, розділ в меню програми.""
    exit 1
fi
echo "Info:\r\r\r\r\r\r\r"Disk and/or partition disk$x$s$y doesn\'\t exist!"\r"Enter the correct drive and partition values ​​in the program menu.""
exit 1
}


DiskMap()
{
lan=`defaults read -g AppleLocale | cut -d "_" -f1`
echo "STOP! Incorrect disk partition!"
if [[ "$lan" = "ru" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Некорректный раздел диска!"\r"Должна быть схема разделов GUID.""
    exit 1
fi
if [[ "$lan" = "uk" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Некоректний розділ диска!"\r"Повинна бути схема розділів GUID.""
    exit 1
fi
echo "Info:\r\r\r\r\r\r\r"Incorrect disk partition!"\r"There shall be GUID Partition Map.""
exit 1
}


DisableDisk()
{
lan=`defaults read -g AppleLocale | cut -d "_" -f1`
echo "STOP! Disk"$x" resource busy!"
if [[ "$lan" = "ru" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Disk"$x" ресурс занят!"\r"Устраните причину."\r"Возможно, вам необходимо перезагрузить компьютер.""
    exit 1
fi
if [[ "$lan" = "uk" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Disk"$x" ресурс зайнятий!"\r"Усуньте причину."\r"Можливо, вам потрібно перезавантажити комп\'\ютер.""
    exit 1
fi
echo "Info:\r\r\r\r\r\r\r"Disk"$x" resource busy!"\r"Eliminate the cause."\r"You may need to restart your computer.""
exit 1
}


DiskFormatGTP()
{
lan=`defaults read -g AppleLocale | cut -d "_" -f1`
echo "STOP! Incorrect partition, or format of disk partition!"
if [[ "$lan" = "ru" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Некорректный раздел, или формат раздела!"\r"Формат должен быть FAT32 или exFAT.""
    exit 1
fi
if [[ "$lan" = "uk" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Некоректне розділ, або формат розділу!"\r"Формат повинен бути FAT32 або exFAT.""
    exit 1
fi
echo "Info:\r\r\r\r\r\r\r"Incorrect partition, or format of disk partition!"\r"The format must be FAT32 or exFAT.""
exit 1
}


DiskFormatMBR()
{
lan=`defaults read -g AppleLocale | cut -d "_" -f1`
echo "STOP! Incorrect partition, or format of disk partition!"
if [[ "$lan" = "ru" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Некорректный раздел, или формат раздела!"\r"Формат должен быть exFAT.""
    exit 1
fi
if [[ "$lan" = "uk" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Некоректне розділ, або формат розділу!"\r"Формат повинен бути exFAT.""
    exit 1
fi
echo "Info:\r\r\r\r\r\r\r"Incorrect partition, or format of disk partition!"\r"The format must be exFAT.""
exit 1
}


IndexNumber()
{
lan=`defaults read -g AppleLocale | cut -d "_" -f1`
echo "STOP! Index: "$i" does not exist in this image!"
if [[ "$lan" = "ru" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Index: "$i" в этом образе не существует!"\r"Введите правильное значение Index в меню программы.""
    exit 1
fi
if [[ "$lan" = "uk" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Index: "$i" у цьому образі не існує!"\r"Введіть правильне значення Index у меню програми.""
    exit 1
fi
echo "Info:\r\r\r\r\r\r\r"Index: "$i" does not exist in this image!"\r"Enter the correct Index value ​​in the program menu.""
exit 1
}


imgTest()
{
lan=`defaults read -g AppleLocale | cut -d "_" -f1`
echo "STOP! The image doesn\'\t exist!"
if [[ "$lan" = "ru" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Образ не существует!"\r"Перетяните на окно программы образ с расширением iso, wim или esd.""
    exit 1
fi
if [[ "$lan" = "uk" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Образ не існує!"\r"Перетягніть на вікно програми образ із розширенням iso, wim або esd.""
    exit 1
fi
echo "Info:\r\r\r\r\r\r\r"The image doesn\'\t exist!"\r"Drag an image with an iso, wim or esd extension onto the program window.""
exit 1
}


Password()
{
lan=`defaults read -g AppleLocale | cut -d "_" -f1`
echo "STOP! Incorrect password!"
if [[ "$lan" = "ru" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Неверный пароль!"\r"Введите пароль администратора.""
    exit 1
fi
if [[ "$lan" = "uk" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Невірний пароль!"\r"Введіть пароль адміністратора.""
    exit 1
fi
echo "Info:\r\r\r\r\r\r\r"Incorrect password!"\r"Enter admin password.""
exit 1
}


NoSystemPartition()
{
s=s
lan=`defaults read -g AppleLocale | cut -d "_" -f1`
echo "STOP! Failed to recover bootloader!"
if [[ "$lan" = "ru" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Не удалось восстановить загрузчик!"\r"Возможно на disk$x$s$y нет системы Windows, или она повреждена.""
    sleep 1
    open /Volumes/EFI/EFI
    exit 1
fi
if [[ "$lan" = "uk" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Неможливо відновити завантажувач!"\r"Можливо, на disk$x$s$y немає системи Windows, або вона пошкоджена.""
    sleep 1
    open /Volumes/EFI/EFI
    exit 1
fi
echo "Info:\r\r\r\r\r\r\r"Failed to recover bootloader!"\r"Perhaps there is no Windows system on disk$x$s$y, or it is damaged.""
sleep 1
open /Volumes/EFI/EFI
exit 1
}


RepairStart()
{
lan=`defaults read -g AppleLocale | cut -d "_" -f1`
if [[ "$lan" = "ru" ]]; then
    echo "Info:\r\r\r\r\r\r\r\r"Восстанавливаем EFI загрузчик Windows.""

elif [[ "$lan" = "uk" ]]; then
    echo "Info:\r\r\r\r\r\r\r\r"Відновлюємо EFI завантажувач Windows.""

else
    echo "Info:\r\r\r\r\r\r\r\r"Restoring the EFI Windows bootloader.""
fi
}


InstallStart()
{
lan=`defaults read -g AppleLocale | cut -d "_" -f1`
ext="${Image##*.}"
if [[ `echo "wim esd" 2>&1 | grep -i $ext` ]]; then
    IndexInf="$(./tools/bin/wimlib-imagex info "$Image" | sed -e s/'Display Name:'//g | sed -e s/'Product Name:'//g | grep 'Index:\|Name:\|Flags:\|System Root:' | grep -v 'Boot' | tr -s ' ' ' ' | sed -e s/'Name:'//g | sed -e s/'System Root:'//g | sed -e s/'Flags:'//g | tr -d "\n")"
    IndexInf=${IndexInf/*'Index: '$i ''/}
    IndexInf=${IndexInf/'Index:'*/}
elif [[ `echo "iso" 2>&1 | grep -i $ext` ]]; then
    IndexInf="$(./tools/bin/wimlib-imagex info /V*/*/sources/install.* | grep 'Index:\|Display Name:' | grep -v 'Boot' | tr -s ' ' ' ' | sed -e s/'Display Name'/'Edition'/g  | tr -d "\n")"
    IndexInf=${IndexInf/*'Index: '$i'Edition: '/}
    IndexInf=${IndexInf/'Index:'*/}
fi
if [[ "$lan" = "ru" ]]; then
    echo "Info:\r\r\r\r\r\r"Устанавливаем"\r"$IndexInf"\r"Продолжительность установки зависит от вашего SSD/HDD накопителя."\r"$remainderTime""

elif [[ "$lan" = "uk" ]]; then
    echo "Info:\r\r\r\r\r\r"Встановлюємо"\r"$IndexInf"\r"Тривалість установки залежить від вашого SSD/HDD накопичувача."\r"$remainderTime""

else
    echo "Info:\r\r\r\r\r\r"Installing"\r"$IndexInf"\r"The installation duration depends on your SSD/HDD drive."\r"$remainderTime""
fi
}


BackupStart()
{
lan=`defaults read -g AppleLocale | cut -d "_" -f1`
if [[ "$lan" = "ru" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Создаём Backup $StartData"\r"$remainderTime""

elif [[ "$lan" = "uk" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Створюємо Backup $StartData"\r"$remainderTime""

else
    echo "Info:\r\r\r\r\r\r\r"Creating Backup $StartData"\r"$remainderTime""
fi
}


Finish()
{
lan=`defaults read -g AppleLocale | cut -d "_" -f1`
if [[ "$lan" = "ru" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Процесс завершён."\r"Времени потрачено: $processedTime""

elif [[ "$lan" = "uk" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Процес завершено."\r"Часу витрачено: $processedTime""

else
    echo "Info:\r\r\r\r\r\r\r"The process is completed."\r"Time is spent: $processedTime""
fi
}


TestDisk()
{
if [[ `diskutil list | grep "disk" | grep -o -e disk"$x"s"$y"` ]]; then
    :
else
    DiskPartition
fi
if [[ "$fwmode" == "uefi" ]]; then
    if [[ `diskutil list | grep "GUID_partition_scheme" | grep -o -e disk"$x"` ]]; then
        :
    else
        DiskMap
    fi
fi
if [[ `diskutil list | grep "Microsoft Basic Data" | grep -o -e disk"$x"s"$y"` || `diskutil list | grep "Windows_NTFS" | grep -o -e disk"$x"s"$y"` ]]; then
    :
else
    scheme=$(diskutil info /dev/disk"$x" | grep "Content (IOContent):" | awk '{print $3}')
    if [[ "$scheme" == "GUID_partition_scheme" ]]; then
    DiskFormatGTP
    else
    DiskFormatMBR
    fi
fi
}


TestIndex()
{

ext="${Image##*.}"
if [[ `echo "wim esd" 2>&1 | grep -i $ext` ]]; then
    pathImage="$Image"
elif [[ `echo "iso" 2>&1 | grep -i $ext` ]]; then
    pathImage=(/V*/*/sources/install.*)
fi
if [[ `./tools/bin/wimlib-imagex info "$pathImage" | tr -s ' ' ' ' | grep 'Index: '$i''` ]]; then
    :
else
    IndexNumber
fi
}


requirements_message ()
{
# Check for required packages that are missing.
if [[ -z $(command -v ./tools/bin/wimlib-imagex) ]]; then missing+=" wimlib-imagex"; fi
if [[ -z $(command -v ./tools/bin/mkntfs) ]]; then missing+=" mkntfs"; fi
if [[ -z $(command -v ./tools/bin/hivexsh) ]]; then missing+=" hivexsh"; fi
if [[ -z $(command -v ./tools/bin/sgdisk) ]]; then missing+=" sgdisk"; fi
if [[ -z $(command -v ./tools/bin/ms-sys) ]]; then missing+=" ms-sys"; fi
if [[ -z $(command -v ./tools/lib/libwim.15.dylib) ]]; then missing+=" libwim.15.dylib"; fi
if [[ -z $(command -v ./tools/lib/libntfs-3g.89.dylib) ]]; then missing+=" libntfs-3g.89.dylib"; fi
if [[ -z $(command -v ./tools/lib/libhivex.0.dylib) ]]; then missing+=" libhivex.0.dylib"; fi
if [[ -z $(command -v ./tools/lib/libpopt.0.dylib) ]]; then missing+=" libpopt.0.dylib"; fi
if [[ -z $(command -v ./tools/lib/libintl.8.dylib) ]]; then missing+=" libintl.8.dylib"; fi
if [[ -z $(command -v ./tools/lib/libreadline.8.2.dylib) ]]; then missing+=" libreadline.8.2.dylib"; fi
if [[ -z $(command -v ./scripts/scriptWIM) ]]; then missing+=" scriptWIM"; fi
if [[ -z $(command -v ./scripts/winload) ]]; then missing+=" scriptWIM"; fi
if [[ -z $(command -v ./scripts/recovery) ]]; then missing+=" recovery"; fi
if [[ -z $(command -v ./scripts/update_device) ]]; then missing+=" update_device"; fi
if [[ ! -z "$missing" ]]; then
lan=`defaults read -g AppleLocale | cut -d "_" -f1`
echo "STOP! The following resources are required: $missing..."
    if [[ "$lan" = "ru" ]]; then
        echo "Info:\r\r\r\r\r\r\r"Требуются следующие ресурсы:"\r"$missing""
        exit 1
    fi
    if [[ "$lan" = "uk" ]]; then
        echo "Info:\r\r\r\r\r\r\r"Потрібні такі ресурси:"\r"$missing""
        exit 1
    fi
    echo "Info:\r\r\r\r\r\r\r"The following resources are required:"\r"$missing""
exit 1
fi
}


SetupComplete()
{
printf "reg add "HKLM\\SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation" /v RealTimeIsUniversal /t REG_DWORD /d 1\n"
printf "cd C:\\\\\n"
printf "attrib +r +s +h bootmgr\n"
printf "attrib +r +s +h BOOTNXT\n"
printf "attrib +r +s +h Boot /d \n"
printf "del /s /q "C:\Windows/Setup/Scripts/SetupComplete.cmd"\n"
}


build_BCD()
{
echo
echo "Build the main BCD store..."
echo "$mypassword" | sudo -S ./scripts/winload "$1" "$2" "$3" "$4" "$5" > "$HOME"/winload.txt
cp -v ./Templates/BCD-Windows "$HOME"/BCD-Windows
./tools/bin/hivexsh -d -w -f "$HOME"/winload.txt "$HOME"/BCD-Windows
if [[ ! $? -eq 0 ]]; then
    echo "Info:\r\r\r\r\r\r\r\r"Failed to create main BCD store.""
    echo
    echo "STOP! Failed to create main BCD store..."
    exit 1
fi
if [[ "$3" == "uefi" ]]; then
    echo
    echo "Build the recovery BCD store..."
    sudo -S ./scripts/recovery "$1" "$4" > "$HOME"/recovery.txt
    cp ./Templates/BCD-Recovery "$HOME"/BCD-Recovery
    ./tools/bin/hivexsh -d -w -f "$HOME"/recovery.txt "$HOME"/BCD-Recovery
    if [[ ! $? -eq 0 ]]; then
        echo "Info:\r\r\r\r\r\r\r\r"Failed to create recovery BCD store.""
        echo
        echo "STOP! Failed to create recovery BCD store..."
        exit 1
    fi
    echo
    echo "Copy the BCD hives to the ESP folders..."
    cp -v "$HOME"/BCD-Windows /Volumes/EFI/EFI/Microsoft/Boot/BCD
    cp -v "$HOME"/BCD-Recovery /Volumes/EFI/EFI/Microsoft/Recovery/BCD
elif [[ "$3" == "bios" ]]; then
      echo
      echo "Copy the main BCD hive to the boot folder..."
      cp -v "$HOME"/BCD-Windows "$HOME"/Boot/BCD
fi
rm "$HOME"/BCD-Windows
rm "$HOME"/winload.txt
if [[ "$3" == "uefi" ]]; then
    rm "$HOME"/recovery.txt
    rm "$HOME"/BCD-Recovery
fi
}


Repair()
{
echo "Media:Creates a bootloader"
RepairStart
echo "Progress:""30""% "

for efi in /Volumes/EFI*; do
  if [[ -e "$efi" ]]; then
      echo=`diskutil unmount force "$efi"`
  fi
done
echo "Progress:""35""% "
if [[ ! -z $(echo "$mypassword" | sudo -S fdisk /dev/disk"$x" | grep -E '2:|3:|4:' | grep -v unused) ]]; then
    printf "p\nedit 2\n0\nedit 3\n0\nedit 4\n0\nq\ny\n" | sudo -S fdisk -e /dev/disk"$x"
fi
diskutil unmount force /dev/disk"$x"s1
echo "$mypassword" | sudo -S fsck_msdos -fy disk"$x"s1 >>/dev/null 2>/dev/null
echo "$mypassword" | sudo -S diskutil mount /dev/disk"$x"s1

if [[ -f "$MountPoint"/Windows/Boot/EFI/bootmgfw.efi ]]; then
    rm -rf /Volumes/EFI/EFI/Microsoft
    mkdir -pv /Volumes/EFI/EFI/Microsoft/Recovery
    cp -rv "$MountPoint"/Windows/Boot/EFI /Volumes/EFI/EFI/Microsoft/BOOT
    cp -rv "$MountPoint"/Windows/Boot/Fonts /Volumes/EFI/EFI/Microsoft/BOOT
    if [[ -d "$MountPoint"/Windows/Boot/Resources ]]; then
        cp -rv "$MountPoint"/Windows/Boot/Resources /Volumes/EFI/EFI/Microsoft/BOOT
    fi
else
    NoSystemPartition
fi

echo "Progress:""70""% "
langCod="$(printf "cd ControlSet001\Control\Nls\Language\nlsval InstallLanguage\nunload\n" | ./tools/bin/hivexsh "$MountPoint/Windows/System32/config/SYSTEM")"
locale="$(printf "cd Microsoft\Input\Locales\loc_"$langCod"\nlsval Fluency Model Directory\nunload\n" | ./tools/bin/hivexsh "$MountPoint/Windows/System32/config/SOFTWARE")"
build_BCD "$x" "$y" "$fwmode" "$locale" "$MountPoint"
echo "Progress:""95""% "

if [[ -e /Volumes/EFI/EFI/Clover ]] || [[ -e /Volumes/EFI/EFI/OC ]]; then
    echo "Don't install BOOT/bootx64.efi"
elif [[ "$bootx64Off" == 1 ]]; then
    echo "Deactivate Windows ESP"
    rm -rf /Volumes/EFI/EFI/BOOT 2>/dev/null
    mkdir -pv /Volumes/EFI/EFI/BOOT
    cp -v /Volumes/EFI/EFI/Microsoft/BOOT/bootmgfw.efi /Volumes/EFI/EFI/BOOT/bootx64.efioff
else
    rm -rf /Volumes/EFI/EFI/BOOT 2>/dev/null
    mkdir -p /Volumes/EFI/EFI/BOOT
    cp -Rv /Volumes/EFI/EFI/Microsoft/BOOT/bootmgfw.efi /Volumes/EFI/EFI/BOOT/bootx64.efi
fi
}


Install()
{
ext="${Image##*.}"
if [[ `echo "iso" 2>&1 | grep -i $ext` ]]; then
    for disk in /Volumes/*/sources/install.*; do
      if [[ -f "$disk" ]]; then
          disk="${disk///sources*}"
          diskutil eject "$disk"
      fi
    done
    hdiutil mount "$Image"
fi

echo "Media:Checking the Index"
TestIndex
InstallStart

if [[ "$fwmode" == "uefi" ]]; then
    if [[ ! -z $(echo "$mypassword" | sudo -S fdisk /dev/disk"$x" | grep -E '2:|3:|4:' | grep -v unused) ]]; then
        printf "p\nedit 2\n0\nedit 3\n0\nedit 4\n0\nq\ny\n" | sudo -S fdisk -e /dev/disk"$x"
    fi
fi

scheme=$(diskutil info /dev/disk"$x" | grep "Content (IOContent):" | awk '{print $3}')
echo "scheme - $scheme"
pstart=$(diskutil info /dev/disk"$x"s"$y" | grep "Partition Offset:" | awk '{print $5}' | sed 's/(//')
echo "pstart - $pstart"
echo "$mypassword" | sudo -S fdisk -y /dev/disk"$x"
if [[ ! $? -eq 0 ]]; then
    DiscNotPermitted
    echo
    echo "STOP! Disk operation not allowed..."
    exit 1
fi

if [[ "$fwmode" == "bios" ]]; then
    echo
    echo "Disable automount disk partitions..."
    echo "$mypassword" | sudo -S rm -rf /etc/fstab 2>/dev/null & sudo -S rm -rf /tmp/fstab 2>/dev/null
    LIST=`diskutil list | grep disk"$x"s`
    echo LIST - "$LIST"
    echo "$LIST" | while read LINE; do
        ID=`echo $LINE | awk '{print $NF}'`
        echo ID - "$ID"
        UUID=`diskutil info "$ID" | grep "Volume UUID" | awk '{print $NF}'`
        TYPE=`diskutil info "$ID" | grep "Type (Bundle)" | awk '{print $NF}'`
        echo "$mypassword" | sudo -S sed -i '' "/$UUID/d" $FSTAB 2>/dev/null
        echo "UUID=$UUID none $TYPE rw,noauto" | sudo -S tee -a $FSTAB 2>/dev/null
        echo "Added $UUID to $FSTAB"
    done
    sudo -S ln -s /tmp/fstab /etc/fstab

    if [[ "$scheme" == "GUID_partition_scheme" ]]; then
        echo
        echo "Partition table conversions to hybrid MBR..."
        sudo -S ./Tools/bin/sgdisk -h $y /dev/disk"$x"
    fi

    echo
    echo "Making the section active..."
    pmbr=$(echo "$mypassword" | sudo -S fdisk /dev/disk"$x" | grep -w $pstart | awk '{print $1}' | sed 's/*//' | sed 's/://')
    echo "\npmbr - $pmbr"
    printf "f $pmbr\nq\ny\n" | sudo -S fdisk -e /dev/disk"$x"
    sudo -S fdisk -y /dev/disk"$x"
fi

diskutil unmount force /dev/disk"$x"s"$y"
echo
echo "Media:Creating NTFS volume structures"
echo "Creating NTFS volume structures..."
sudo -S ./Tools/bin/mkntfs -p "$pstart" -S 63 -H 255 -f -L "$VolumeName" /dev/disk"$x"s"$y"

if [[ "$fwmode" == "bios" ]]; then
    diskutil unmountDisk force /dev/disk"$x"
    sleep 1
    echo
    echo "Media:Create Windows boot record"
    echo "Create Windows boot record..."
    echo "$mypassword" | sudo -S ./tools/bin/ms-sys -7 /dev/disk"$x" || DisableDisk
    sleep 2
    diskutil unmount force /dev/disk"$x"s"$y"
    sudo -S ./tools/bin/ms-sys -n -p /dev/disk"$x"s"$y"
    sleep 1
    diskutil unmountDisk force /dev/disk"$x"
    echo
    echo "Media:Windows Disk Signature to the MBR"
    echo "Windows Disk Signature to the MBR..."
    sudo -S dd if=/dev/random of=/dev/disk"$x" bs=1 count=4 seek=440
    sleep 2
fi

diskutil unmount force /dev/disk"$x"s"$y"
ext="${Image##*.}"
if [[ `echo "wim esd" 2>&1 | grep -i $ext` ]]; then
    pathImage="$Image"
elif [[ `echo "iso" 2>&1 | grep -i $ext` ]]; then
    pathImage=(/V*/*/sources/install.*)
fi

echo
echo "Install $pathImage to /dev/disk"$x"s"$y"..."
sudo -S ./Tools/bin/wimlib-imagex apply "$pathImage" "$i" /dev/disk"$x"s"$y" 2>&1 |
while IFS= read -d $'\r' -r p; do
  echo "Windows Install disk"$x"s"$y" "$p""
  inst=${p/(*/}

  if [[ `echo "$p" | grep -w "Creating"` ]]; then
      pr=${p/*(/}
      pr=${pr/"%"*}
      echo "Media:"$inst""
  elif [[ `echo "$p" | grep -w "Extracting"` ]]; then
      pr=${p/*(/}
      pr=${pr/"%"*}
      pr=$(($pr+100))
      echo "Media:"$inst""
  fi

  if [[ "$pr" -gt "0" ]]; then
      prr=$(($pr/2))
  else
      prr=0
  fi 2>/dev/null
  echo "Progress:""$prr""% "
  InstallStart
  tempTime=$(date -u "+%s")
  if [[ "$prOld" -lt "$pr" ]] && [[ "$tempTimeOld" -lt "$tempTime" ]]; then
      prRem=$(expr 200 - $pr)
      processedTime=$(expr "$tempTime" - "$tempTimeOld")
      remTime=$(expr $prRem \* $processedTime)

      if [[ $remTimeOld -gt "0" ]]; then
          remTime=$(expr $remTime + $remTimeOld)
          remTime=$(expr $remTime / 2)
      fi
      remTimeOld=$remTime

      if [[ $remTime -gt 3599 ]]; then
          remainderTime=$(printf "%dh%dm\n" $((remTime/3600%3600)) $((remTime/60%60)))

      elif [[ $remTime -gt 59 ]]; then
          remainderTime=$(printf "%dm%ds\n" $((remTime/60%60)) $((remTime%60)))

      elif [[ $remTime -gt "0" ]]; then
          remainderTime=$(printf "%ds\n" $((remTime)))
      fi
      tempTimeOld="$tempTime"
  fi 2>/dev/null
  prOld="$pr"
done

echo "Media:Creates a bootloader"
diskutil mount /dev/disk"$x"s"$y"

if [[ "$fwmode" == "uefi" ]]; then
    echo
    echo "Creates a bootloader..."
    for efi in /Volumes/EFI*; do
      if [[ -e "$efi" ]]; then
          echo=`diskutil unmount force "$efi"`
      fi
    done
    diskutil unmount force /dev/disk"$x"s1
    echo "$mypassword" | sudo -S fsck_msdos -fy disk"$x"s1 >>/dev/null 2>/dev/null
    echo "$mypassword" | sudo -S diskutil mount /dev/disk"$x"s1
    rm -rf /Volumes/EFI/EFI/Microsoft
    mkdir -pv /Volumes/EFI/EFI/Microsoft/Recovery
    cp -rv "$MountPoint"/Windows/Boot/EFI /Volumes/EFI/EFI/Microsoft/BOOT
    cp -rv "$MountPoint"/Windows/Boot/Fonts /Volumes/EFI/EFI/Microsoft/BOOT
    if [[ -d "$MountPoint"/Windows/Boot/Resources ]]; then
        cp -rv "$MountPoint"/Windows/Boot/Resources /Volumes/EFI/EFI/Microsoft/Boot
    fi
    
    langCod="$(printf "cd ControlSet001\Control\Nls\Language\nlsval InstallLanguage\nunload\n" | ./tools/bin/hivexsh "$MountPoint/Windows/System32/config/SYSTEM")"
    locale="$(printf "cd Microsoft\Input\Locales\loc_"$langCod"\nlsval Fluency Model Directory\nunload\n" | ./tools/bin/hivexsh "$MountPoint/Windows/System32/config/SOFTWARE")"
    build_BCD  "$x" "$y" "$fwmode" "$locale" "$MountPoint"
    
    if [[ -e /Volumes/EFI/EFI/Clover ]] || [[ -e /Volumes/EFI/EFI/OC ]]; then
        echo
        echo "Don't install BOOT/bootx64.efi..."
    elif [[ "$bootx64Off" == 1 ]]; then
        echo
        echo "Deactivate Windows ESP..."
        rm -rf /Volumes/EFI/EFI/BOOT 2>/dev/null
        mkdir -pv /Volumes/EFI/EFI/BOOT/
        cp -v /Volumes/EFI/EFI/Microsoft/BOOT/bootmgfw.efi /Volumes/EFI/EFI/BOOT/bootx64.efioff
    else
        rm -rf /Volumes/EFI/EFI/BOOT 2>/dev/null
        mkdir -pv /Volumes/EFI/EFI/BOOT/
        cp -v /Volumes/EFI/EFI/Microsoft/BOOT/bootmgfw.efi /Volumes/EFI/EFI/BOOT/bootx64.efi
    fi
    KernOSRelease=`sysctl -n kern.osrelease | cut -d "." -f1`
    if [[ ${KernOSRelease} < "22" ]]; then
        mkdir ~/ntfs-volume
        echo "$mypassword" | sudo -S umount /dev/disk"$x"s"$y"
        sudo -S mount -t ntfs -o rw,auto,nobrowse /dev/disk"$x"s"$y" ~/ntfs-volume
        if [[ ! -f ~/ntfs-volume/Windows/Setup/Scripts/SetupComplete.cmd ]]; then
            mkdir -p ~/ntfs-volume/Windows/Setup/Scripts
            echo "reg add "HKLM\\SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation" /v RealTimeIsUniversal /t REG_DWORD /d 1" >> ~/ntfs-volume/Windows/Setup/Scripts/SetupComplete.cmd
        fi
        sudo -S umount /dev/disk"$x"s"$y"
        rm -r ~/ntfs-volume
    fi
fi

if [[ "$fwmode" == "bios" ]]; then
    echo
    echo "Creating a "Boot" folder and creating bootloader files..."
    diskutil mount /dev/disk"$x"s"$y"
    cp -rv "$MountPoint"/Windows/Boot/PCAT "$HOME"/Boot
    cp -rv "$MountPoint"/Windows/Boot/Fonts "$HOME"/Boot
    if [[ -d "$MountPoint"/Windows/Boot/Resources ]]; then
        cp -rv "$MountPoint"/Windows/Boot/Resources "$HOME"/Boot
    fi
    if [[ ! -f "$HOME"/Boot/bootmgr ]]; then
        cp -v "$MountPoint"/Windows/Boot/PCAT/* "$HOME"/Boot/
    fi
    mv "$HOME"/Boot/bootmgr "$HOME"
    if [[ -f "$MountPoint"/Windows/Boot/PCAT/bootnxt ]]; then
        mv "$HOME"/Boot/bootnxt "$HOME"/BOOTNXT
    fi
    langCod="$(printf "cd ControlSet001\Control\Nls\Language\nlsval InstallLanguage\nunload\n" | ./tools/bin/hivexsh "$MountPoint/Windows/System32/config/SYSTEM")"
    locale="$(printf "cd Microsoft\Input\Locales\loc_"$langCod"\nlsval Fluency Model Directory\nunload\n" | ./tools/bin/hivexsh "$MountPoint/Windows/System32/config/SOFTWARE")"
    build_BCD  "$x" "$y" "$fwmode" "$locale" "$MountPoint"
    echo
    echo "Copy the BIOS boot files to the system partition..."
    KernOSRelease=`sysctl -n kern.osrelease | cut -d "." -f1`
    if [[ ${KernOSRelease} < "22" ]]; then
        mkdir "$HOME"/ntfs-volume
        if [[ ! -f "$MountPoint/bootmgr" || ! -d "$MountPoint/Boot" ]]; then
            echo "$mypassword" | sudo -S umount /dev/disk"$x"s"$y"
            sudo -S mount -t ntfs -o rw,auto,nobrowse /dev/disk"$x"s"$y" "$HOME"/ntfs-volume
            cp -rv "$HOME"/Boot "$HOME"/ntfs-volume
            cp -v "$HOME"/bootmgr "$HOME"/ntfs-volume
            if [[ -f "$HOME"/BOOTNXT ]]; then
                cp -v "$HOME"/BOOTNXT "$HOME"/ntfs-volume
            fi
            if [[ ! -f "$HOME"/ntfs-volume/Windows/Setup/Scripts/SetupComplete.cmd ]]; then
                 echo "$MountPoint/Windows/Setup/Scripts/SetupComplete.cmd - creation"
                 mkdir -pv "$HOME"/ntfs-volume/Windows/Setup/Scripts
                 SetupComplete >> "$HOME"/ntfs-volume/Windows/Setup/Scripts/SetupComplete.cmd
            else
                 echo "$MountPoint/Windows/Setup/Scripts/SetupComplete.cmd - record"
                 cp -v "$HOME"/ntfs-volume/Windows/Setup/Scripts/SetupComplete.cmd "$HOME"
                 SetupComplete >> "$HOME"/SetupComplete.cmd
                 cp -fv "$HOME"/SetupComplete.cmd "$HOME"/ntfs-volume/Windows/Setup/Scripts/SetupComplete.cmd
                 rm -r "$HOME"/SetupComplete.cmd
            fi
        else
            echo "$mypassword" | sudo -S umount /dev/disk"$x"s"$y"
            sudo -S mount -t ntfs -o rw,auto,nobrowse /dev/disk"$x"s"$y" "$HOME"/ntfs-volume
            cp -fv "$HOME"/Boot/BCD "$HOME"/ntfs-volume/Boot/
        fi
        echo "$mypassword" | sudo -S umount /dev/disk"$x"s"$y"
        rm -r "$HOME"/ntfs-volume
        rm -r "$HOME"/Boot
        rm -r "$HOME"/bootmgr
        if [[ -f "$HOME"/BOOTNXT ]]; then
            rm -r "$HOME"/BOOTNXT
        fi
    else
        mkdir -pv "$HOME/Desktop/Legacy boot for Windows (disk"$x"s"$y")"
        cp -rv "$HOME"/Boot "$HOME/Desktop/Legacy boot for Windows (disk"$x"s"$y")"
        cp -v "$HOME"/bootmgr "$HOME/Desktop/Legacy boot for Windows (disk"$x"s"$y")"
        if [[ -f "$HOME"/BOOTNXT ]]; then
            cp -v "$HOME"/BOOTNXT "$HOME/Desktop/Legacy boot for Windows (disk"$x"s"$y")"
            rm -r "$HOME"/BOOTNXT
        fi
        rm -r "$HOME"/Boot
        rm -r "$HOME"/bootmgr
    fi
    sudo -S rm -rf /etc/fstab
fi
echo "Media:Creates a bootloader ... Complete"
diskutil mount /dev/disk"$x"s"$y"
}


Backup()
{
diskutil unmount force /dev/disk"$x"s"$y"
if [[ "$(./tools/bin/wimlib-imagex info "$DestinationFolder/WindowsBackup.wim")" ]]; then
    meaning=append
else
    meaning=capture
fi 2>/dev/null

StartData="$(date +"%Y-%m-%d-%H:%M")"

echo "$mypassword" | sudo -S ./Tools/bin/wimlib-imagex "$meaning" --compress=fast --check --config=./Exclusion_List.ini /dev/disk"$x"s"$y" "$DestinationFolder/WindowsBackup.wim" "Backup $(date +"%Y-%m-%d-%H:%M")" 2>&1 |
while IFS= read -d $'\r' -r p; do
  echo "Windows Backup disk"$x"s"$y" "$p""

  if [[ `echo "$p" | grep -w "scanned"` ]]; then
      inst=${p}
      pr=0
  elif [[ `echo "$p" | grep -w "integrity"` ]]; then
      inst=${p/(*/}
      inst=$(echo $inst | sed -e s/' integrity table'//g)
      inst=$(echo $inst | sed -e s!" of ""\"$DestinationFolder/WindowsBackup.wim"\"!!g)
      #pr=0
  else
      inst=${p/(*/}
      pr=${p/*(/}
      pr=${pr/"%"*}
  fi

  echo "Media:"$inst""
  BackupStart

  if [[ "$pr" -gt "0" ]]; then
      echo "Progress:""$pr""% "
  else
      echo "Progress:""0""% "
  fi 2>/dev/null

  tempTime=$(date -u "+%s")
  if [[ "$prOld" -lt "$pr" ]] && [[ "$tempTimeOld" -lt "$tempTime" ]]; then
      prRem=$(expr 100 - $pr)
      processedTime=$(expr $tempTime - $tempTimeOld)
      remTime=$(expr $prRem \* $processedTime)

      if [[ $remTimeOld -gt "0" ]]; then
          remTime=$(expr $remTime + $remTimeOld)
          remTime=$(expr $remTime / 2)
      fi
      remTimeOld=$remTime

      if [[ $remTime -gt 3599 ]]; then
          remainderTime=$(printf "%dh%dm\n" $((remTime/3600%3600)) $((remTime/60%60)))

      elif [[ $remTime -gt 59 ]]; then
          remainderTime=$(printf "%dm%ds\n" $((remTime/60%60)) $((remTime%60)))

      elif [[ $remTime -gt "0" ]]; then
          remainderTime=$(printf "%ds\n" $((remTime)))
      fi
      tempTimeOld="$tempTime"
  fi &> /dev/null
  prOld="$pr"
done
diskutil mount /dev/disk"$x"s"$y"
}

##################################################################################
###### Start script execution routine ############################################
##################################################################################
echo "TextPosition:Center"
echo "Media: "
echo "Media:Password verification"
echo "Info: "
sleep 0.5
requirements_message
passWinInstal=Mac-"$(ioreg -rd1 -c IOPlatformExpertDevice | awk '/IOPlatformUUID/' | cut -f2 -d"=" | tr -d '" ' | cut -f5-5 -d '-' | tr -d - | rev)"
mypassword=$(security find-generic-password -wl ${passWinInstal} 2>/dev/null)
echo "$mypassword" | sudo -S echo "Ok" || Password

WindowsInstallPlist="$HOME/Library/Preferences/org.SerhiiHalan.SettingsWindowsInstall.plist" &> /dev/null
DestinationFolder="$(/usr/libexec/PlistBuddy -c "Print :DestinationFolder" "$WindowsInstallPlist")"
Image="$(/usr/libexec/PlistBuddy -c "Print :ImageWIM" "$WindowsInstallPlist")"
Mode="$(defaults read $WindowsInstallPlist PMode)"
bootx64Off="$(defaults read $WindowsInstallPlist bootx64)"
i="$(defaults read $WindowsInstallPlist DIndex)"
x="$(defaults read $WindowsInstallPlist DNumber)"
y="$(defaults read $WindowsInstallPlist DPartition)"

Mounted=$(diskutil info disk"$x"s"$y" | sed -n 's/.*Mounted: *//p')
if [[ $Mounted == No ]]; then
    diskutil mount /dev/disk"$x"s"$y"
fi

MountPoint=`diskutil info disk"$x"s"$y" | sed -n 's/.*Mount Point: *//p'`
if [[ -d "$MountPoint" ]]; then
    VolumeName="${MountPoint##*/}"
else
    MountPoint=/Volumes/Windows
    VolumeName=Windows
fi
FSTAB=/private/tmp/fstab
echo MountPoint - "$MountPoint"

if [[ $Mode ==  "Restore EFI bootloader" ]]; then
    echo "################### START Repair ####################"
    fwmode="uefi"
    csrutil status
    sw_vers
    echo "Model ID:      "`sysctl -n hw.model`
    echo "Progress:""0""% "
    diskutil list
    startTime=$(date -u "+%s")
    echo "Progress:""20""% "
    TestDisk
    Repair
    echo "Progress:""100""% "
    Time
    Finish
    afplay sound/WindowsUnlock.wav &> /dev/null

    echo "Media:Creates a bootloader ... Complete"
    echo "... Complete"
    echo "... Time is spent: $processedTime"
    echo "... Current time: $(date "+%Y-%m-%d %H:%M:%S %z")"
    echo "######################## End ########################"

    echo "NOTIFICATION:Complete: disk"$x"s"$y"\rTime is spent: $processedTime\rTime: $(date "+%Y-%m-%d %H:%M:%S %z")"
    open /Volumes/EFI/EFI
    exit



elif [[ $Mode == "Windows Backup" ]]; then
    echo "################## START Backup ###################"
    mkdir "$DestinationFolder" &> /dev/null
    csrutil status
    sw_vers
    echo "Model ID:      "`sysctl -n hw.model`
    echo "Progress:""0""% "
    diskutil list
    startTime=$(date -u "+%s")
    echo "Media:Checking the disk and partition"
    TestDisk
    Backup
    echo "Progress:""100""% "
    Time
    Finish
    afplay sound/WindowsUnlock.wav &> /dev/null

    #echo "Media:... Complete"
    echo "... Complete"
    echo "... Time is spent: $processedTime"
    echo "... Current time: $(date "+%Y-%m-%d %H:%M:%S %z")"
    echo "######################## End ########################"

    echo "NOTIFICATION:Complete: disk"$x"s"$y"\rTime is spent: $processedTime\rTime: $(date "+%Y-%m-%d %H:%M:%S %z")"
    exit



elif [[ -f "$Image" ]] && [[ $Mode == "Install Windows UEFI" ]]; then
    echo "################## START Install ###################"
    fwmode="uefi"
    csrutil status
    sw_vers
    echo "Model ID:      "`sysctl -n hw.model`
    echo "Progress:""0""% "
    diskutil list
    startTime=$(date -u "+%s")
    echo "Media:Checking the disk and partition"
    TestDisk
    Install
    echo "Progress:""100""% "
    Time
    Finish
    afplay sound/WindowsUnlock.wav &> /dev/null

    echo "... Complete"
    echo "... Time is spent: $processedTime"
    echo "... Current time: $(date "+%Y-%m-%d %H:%M:%S %z")"
    echo "######################## End ########################"

    echo "NOTIFICATION:Complete: disk"$x"s"$y"\rTime is spent: $processedTime\rTime: $(date "+%Y-%m-%d %H:%M:%S %z")"
    for disk in /Volumes/*/sources/install.*; do
      if [[ -f "$disk" ]]; then
          disk="${disk///sources*}"
          diskutil eject "$disk"
      fi
    done
    open /Volumes/EFI/EFI
    open "$MountPoint"
    exit



elif [[ -f "$Image" ]] && [[ $Mode == "Install Windows legacy boot" ]]; then
    echo "################## START Install ###################"
    fwmode="bios"
    csrutil status
    sw_vers
    echo "Model ID:      "`sysctl -n hw.model`
    echo "Progress:""0""% "
    diskutil list
    startTime=$(date -u "+%s")
    echo "Media:Checking the disk and partition"
    TestDisk
    Install
    echo "Progress:""100""% "
    Time
    Finish
    afplay sound/WindowsUnlock.wav &> /dev/null

    echo "... Complete"
    echo "... Time is spent: $processedTime"
    echo "... Current time: $(date "+%Y-%m-%d %H:%M:%S %z")"
    echo "######################## End ########################"

    echo "NOTIFICATION:Complete: disk"$x"s"$y"\rTime is spent: $processedTime\rTime: $(date "+%Y-%m-%d %H:%M:%S %z")"
    for disk in /Volumes/*/sources/install.*; do
      if [[ -f "$disk" ]]; then
          disk="${disk///sources*}"
          diskutil eject "$disk"
      fi
    done
    echo "$mypassword" | sudo -S rm -rf /etc/fstab 2>/dev/null & sudo -S rm -rf /tmp/fstab 2>/dev/null
    open "$MountPoint"
    exit
else
    imgTest
fi
exit
